<%@ page contentType="application/json;charset=UTF-8" language="java" %><%--
--%><%@ page import="java.util.ArrayList" %><%--
--%><%@ page import="java.util.Collections" %><%--
--%><%@ page import="java.util.List" %><%--
--%><%@ page import="spacecrack.NameRandomizer" %><%--
--%><%@ page import="spacecrack.Player" %><%--
--%><%@ page import="spacecrack.PlayerManager" %><%--
--%><%@ page import="o.json.JSONFactory" %><%--
--%><%@ page import="o.json.JSONWriter" %><%--
--%><%--@ include file="players.json" --%><%--
--%><%

	System.out.println(Collections.list(request.getParameterNames()));

	final PlayerManager pm = new PlayerManager();

	String action = request.getParameter("action");
	String id     = request.getParameter("id");
	String name   = request.getParameter("name");

	if (action == null) {
		System.out.println("Load");
	}
	if (action != null && action.equalsIgnoreCase("clear")) {
		System.out.println("Clear");
		pm.clearPlayers();
	}
	if (action != null && action.equalsIgnoreCase("create")) {
		System.out.println("Create");

		final String pId   = (id   != null && id   != "") ?
			id   : NameRandomizer.get(5) +"@test.com";
		final String pName = (name != null && name != "") ?
			name : NameRandomizer.get(10);

		if (!pm.playerExists(pId)) {
			final Player player = new Player(pId, pName);
			pm.storePlayer(player);
		}
	}

	final List<Player> players = new ArrayList<Player>();
	if (id != null && id != "") {
		if (pm.playerExists(id)) {
			players.add(pm.loadPlayerById(id));
		}
	} else {
		players.addAll(pm.loadPlayers());
	}
	System.out.println(players);

	final JSONWriter writer = new JSONWriter();
	final JSONFactory f = new JSONFactory();
	writer.write(f.create(players));

%><%= writer.toString() %>
